var prefix = jsctx + "/member/level";
var level = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $(".fixed-table-header-columns").css("display", "none");
        $(".fixed-table-body-columns").css("display", "none");
        $('#exampleTable').bootstrapTable('refresh');
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                levelName: $('#levelName').val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listPageMemberLevel",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageList: [10, 20, 30],
                pageSize: 10,
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                height: h,
                paginationShowPageGo: true,
                rightFixedColumns: false,
                showColumns: true,
                queryParams: function (params) {
                    return {
                        pageSize: params.limit,
                        pageNo: (params.offset / params.limit) + 1,
                        levelName: $("#levelName").val().trim(),
                    };
                },
                columns: [
                    {
                        field: 'number',
                        title: '序号',
                        width: '50', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'memberLevel', title: '等级名称', align: 'center', width: '100'},
                    {field: 'levelSub', title: '子等级', width: '100', align: 'center'},
                    {
                        field: 'cycleType', title: '周期', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (value == '0') {
                                return "年";
                            } else {
                                return "永久";
                            }
                        }
                    },
                    {
                        field: 'levelLogo', title: '会员标识', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (value != null && value != '') {
                                return "<img src=" + value + " width='50px' height='50px'>";
                            }
                        }

                    },

                    {field: 'rechargeAmount', title: '充值金额', width: '100', align: 'center'},
                    {field: 'discountAmount', title: '消费折扣', width: '100', align: 'center'},
                    {field: 'createdTime', title: '创建时间', width: '100', align: 'center'},
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '200', align: 'center',
                        class: '',
                        formatter: function (value, row, index) {
                            if (row.memberLevel == 'V0' ) {
                                return ;
                            }
                            var a = '';
                            var b = '';
                            a = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="详情" onclick="level.edit(\''
                                + row.levelSub + '\')">编辑</a> ';
                            b = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="详情" onclick="level.deleteLevel(\''
                                + row.levelSub + '\')">删除</a> ';
                            var  c = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="权益设置" onclick="level.gainSetting(\''
                                + row.levelSub + '\')">权益设置</a> ';
                            return a + b + c;


                        }
                    }
                ]
            });
    };

    function updateChargeStatus(memberId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateChargeStatus",
                type: "post",
                data: {
                    'memberId': memberId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function addLevel() {
        location.href = jsctx + "/member/level/addLevel";
    }

    function edit(levelSub) {
        location.href = prefix + "/edit/" + levelSub;
    }

    function gainSetting(levelSub) {
        location.href = jsctx + "/member/gain/indexWithSublevel/" + levelSub;
    }

    function editLevel(levelSub) {
        $.ajax({
            url: prefix + "/delete",
            type: "post",
            data: {
                'levelSub': levelSub
            },
            success: function (data) {
                layer.close(index);
                if (data.status == 200) {
                    layer.msg("删除成功");
                    reLoad();
                } else {
                    layer.msg(data.message);
                }
            }
        });
    }

    function deleteLevel(levelSub) {
        layer.confirm('确定删除次会员等级信息？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/delete",
                type: "post",
                data: {
                    'levelSub': levelSub
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }


    function exportMemberInfo() {
        $.fileDownload(prefix + "/exportMemberInfo", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                mobile: $("#mobile").val().trim(),
                memberType: $("#memberType").val().trim(),
                status: $("#status").val().trim(),
                chargeStatus: $("#chargeStatus").val().trim(),
                nickname: $("#nickname").val().trim(),
                remark: $("#remark").val().trim(),
                startTime: $("#startTime").val().trim(),
                endTime: $("#endTime").val().trim(),
                count: $("#count").val().trim() == '' ? 0 : $("#count").val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    return {
        init: init,
        reLoad: reLoad,
        addLevel: addLevel,
        edit: edit,
        deleteLevel: deleteLevel,
        updateChargeStatus: updateChargeStatus,
        exportList: exportList,
        gainSetting: gainSetting,
    };
})();


var addLevel = (function () {
    function init() {
        validateRule();
    };

    var isajaxsend = true;

    function save() {
        if (isajaxsend) {
            var formData = new FormData($("#frmLevel")[0]);
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveLevel",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmLevel").validate({
            rules: {
                levelName: {
                    required: true
                }
            },
            messages: {
                levelName: {
                    required: icon + "请输入等级名称"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };


})();

var editLevel = (function () {
    function save() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function editLevel() {
        if (isajaxsend) {
            var formData = new FormData($("#frmLevel")[0]);
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/frmLevel",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        // window.history.back();
                    } else {
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmLevel").validate({
            rules: {
                levelName: {
                    required: true
                }
            },
            messages: {
                levelName: {
                    required: icon + "请输入等级名称"
                }
            },
            submitHandler: function (form) {
                editLevel();
            }
        })
    }

    return {
        save: save
    };


})();
